package com.sunyard.pcc.shiro.filter;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @Author: Hewei
 * @Description:
 * @Date: Created in 9:57 2018/4/2
 */

/**
 * Created by zhenmo on 17/8/16 17:49.
 */
@Profile({"local", "dev"})
@Configuration
@WebFilter(urlPatterns = "/**")
public class CorsFilter extends OncePerRequestFilter {
    private static final String ALLOWORIGIN_CORS_ALL = "*";
    private static final String MAX_CORS_AGE = "3600";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain
            filterChain) throws ServletException, IOException {
        // Access-Control-Allow-Origin: 指定授权访问的域
        response.addHeader("Access-Control-Allow-Origin", ALLOWORIGIN_CORS_ALL);  //此优先级高于@CrossOrigin配置

        // Access-Control-Allow-Methods: 授权请求的方法（GET, POST, PUT, DELETE，OPTIONS等)
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");

        response.addHeader("Access-Control-Allow-Headers", "Content-Type");

        response.addHeader("Access-Control-Max-Age", MAX_CORS_AGE);
        filterChain.doFilter(request, response);
    }
}